package com.wetao.lib_common.utils;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;

import androidx.core.app.ActivityCompat;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.tencent.smtt.utils.FileUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * ComUtil
 */
public class ComUtil {

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
        } else {
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static boolean validatePass(String pass) {
        String passRegex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
        return !TextUtils.isEmpty(pass) && pass.matches(passRegex);
    }

    public static void changeStatusBarTextColor(Context context, boolean isBlack) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (isBlack) {
                //设置状态栏黑色字体
                ((Activity) context).getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                        View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            } else {
                //恢复状态栏白色字体
                ((Activity) context).getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

            }
        }
    }

    public static boolean isChinaPhoneLegal(String str)
            throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public static boolean isChinese(String str) {
        Pattern pattern = Pattern.compile("^[\\u4E00-\\u9FA5]+$");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    //long型时间转换为字符串时间类型
    public static String longToString(Object longTime, String timeFormat) {
        SimpleDateFormat formatter = new SimpleDateFormat(timeFormat == null ? "yyyy-MM-dd" : timeFormat);
        long time = 0;
        if (longTime instanceof Integer || longTime instanceof Long) {
            return formatter.format(longTime);
        } else if (longTime instanceof String) {
            return formatter.format(Long.valueOf((String) longTime));
        }
        return "时间获取错误";
    }


    public static String stringForTime(int timeMs) {
        StringBuilder mFormatBuilder = new StringBuilder();
        int totalSeconds = timeMs / 1000;
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        mFormatBuilder.setLength(0);
        Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }


    /**
     * 判断wifi是否连接
     *
     * @param context
     * @return
     */
    public static boolean isWifiConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetworkInfo.isConnected()) {
            return true;
        }
        return false;
    }

    //检查是否有可用网络
    public static boolean isNetworkConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) ConstantUtils.getAPPContext().
                getSystemService(Context.CONNECTIVITY_SERVICE);
        assert connectivityManager != null;
        return connectivityManager.getActiveNetworkInfo() != null;
    }

    // 屏幕宽度（像素）
    public static int getScreenWidth(Context context) {
        DisplayMetrics metric = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metric);
        return metric.widthPixels;
    }

    public static int getScreenHeight(Context context) {
        DisplayMetrics metric = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metric);
        return metric.heightPixels;
    }

    public static String getMd5Str(HashMap<String, String> map) {
        StringBuffer sb = new StringBuffer();
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            sb.append(entry.getValue().toString());
        }
        return MD5Utils.getMd5(sb.toString());
    }

    public static HashMap<String, String> getHashmapByStr(String[] keyArray, String[] valueArray) {
        HashMap<String, String> map = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        if (keyArray.length != valueArray.length) {
            ToastUtil.initToast("key value长度不对应");
        } else {
            for (int i = 0; i < keyArray.length; i++) {
                map.put(keyArray[i], valueArray[i]);
            }
            return map;
        }
        return null;
    }

    public static Map<String, Object> getHashmapByStr(String[] keyArray, Object[] valueArray) {
        HashMap<String, Object> map = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        if (keyArray.length != valueArray.length) {
            ToastUtil.initToast("key value长度不对应");
        } else {
            for (int i = 0; i < keyArray.length; i++) {
                map.put(keyArray[i], valueArray[i]);
            }
//            for (int i = 0; i < valueArray.length; i++) {
//                sb.append(valueArray[i]);
//            }
//            map.put("secret", MD5Utils.getMd5(sb.toString()));
            return map;
        }
        return null;
    }


    /*
     * 判断服务是否启动,context上下文对象 ，className服务的name
     */
    public static boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(30);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }


    public static String createFileName(final String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        int start = url.lastIndexOf("/");
        if (-1 == start) {
            return null;
        }
        return url.substring(start + 1);
    }


    /**
     * 生成二维码
     *
     * @param contentUrl
     * @param widthPix
     * @param heightPix
     * @param filePath
     * @return
     */
    public static boolean createQRImage(String contentUrl, int widthPix, int heightPix, String filePath) {
        try {
            if (contentUrl == null || "".equals(contentUrl)) {
                return false;
            }

            //配置参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //容错级别
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            //设置空白边距的宽度
            hints.put(EncodeHintType.MARGIN, 2); //default is 4

            // 图像数据转换，使用了矩阵转换
            BitMatrix bitMatrix = new QRCodeWriter().encode(contentUrl, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
            int[] pixels = new int[widthPix * heightPix];
            // 下面这里按照二维码的算法，逐个生成二维码的图片，
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < heightPix; y++) {
                for (int x = 0; x < widthPix; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * widthPix + x] = 0xff000000;
                    } else {
                        pixels[y * widthPix + x] = 0xffffffff;
                    }
                }
            }

            // 生成二维码图片的格式，使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);


            //必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的，内存消耗巨大！
            return bitmap != null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath));
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }

        return false;
    }


    /**
     * 二维码生成图片
     *
     * @param str
     * @return
     */
    public static Bitmap Create2DCode(String str) {
        if (str == null) return null;
        //生成二维矩阵,编码时要指定大小,
        //不要生成了图片以后再进行缩放,以防模糊导致识别失败
        try {
            //配置参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //容错级别
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            //设置空白边距的宽度
            hints.put(EncodeHintType.MARGIN, 1); //default is 4
            BitMatrix matrix = new QRCodeWriter().encode(str, BarcodeFormat.QR_CODE, 256, 256, hints);
            int width = matrix.getWidth();
            int height = matrix.getHeight();
            //  二维矩阵转为一维像素数组（一直横着排）
            int[] pixels = new int[width * height];
            // 下面这里按照二维码的算法，逐个生成二维码的图片，
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (matrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000;
                    } else {
                        pixels[y * width + x] = 0xffffffff;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            // 通过像素数组生成bitmap, 具体参考api
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String getIMEI(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Activity.TELEPHONY_SERVICE);
        if (tm != null) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling

                return "";
            }
            return tm.getDeviceId();
        }
        return null;
    }

    /**
     * @param slotId slotId为卡槽Id，它的值为 0、1；
     * @return
     */
    public static String getIMEI(Context context, int slotId) {
        try {
            TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            Method method = manager.getClass().getMethod("getImei", int.class);
            String imei = (String) method.invoke(manager, slotId);
            return imei;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 从dp单位转换为px
     *
     * @param dp dp值
     * @return 返回转换后的px值
     */
    public static int dp2px(int dp) {
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
    }


    public static boolean isWifiOpened(Context context) {
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        return wifiManager.isWifiEnabled();
    }


    /**
     * 计算文件大小
     *
     * @param byteNum
     * @return
     */
    public static String byte2FitMemorySize(final long byteNum) {
        if (byteNum < 0) {
            return "shouldn't be less than zero!";
        } else if (byteNum < 1024) {
            return String.format(Locale.getDefault(), "%.0fB", (double) byteNum);
        } else if (byteNum < 1048576) {
            return String.format(Locale.getDefault(), "%.0fKB", (double) byteNum / 1024);
        } else if (byteNum < 1073741824) {
            return String.format(Locale.getDefault(), "%.0fMB", (double) byteNum / 1048576);
        } else {
            return String.format(Locale.getDefault(), "%.0fGB", (double) byteNum / 1073741824);
        }
    }


    //计算间隔时间
    public static String calculateLastTime(long time) {
        String result = "";
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        long ns = 1000;
        if (time > 0) {
            long day = time / nd;
            if (day > 0) {
                result += day + "天前";
                return result;
            }
            // 计算差多少小时
            long hour = time % nd / nh;
            if (hour > 0) {
                result += hour + "小时前";
                return result;
            }
            // 计算差多少分钟
            long min = time % nd % nh / nm;
            // 计算差多少秒//输出结果
            // 输出 相差n天n小时n分钟n毫秒
            if (min > 0) {
                result += min + "分钟前";
                return result;
            }
        }
        return "刚刚";
    }

    /**
     * 判断某activity是否处于栈顶
     *
     * @return true在栈顶 false不在栈顶
     */
    public static boolean isActivityTop(Activity activity, Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        System.out.println("name=" + name);

        System.out.println("name=" + activity.getLocalClassName());
        System.out.println("name=" + activity.getPackageName());
        return name.equals(activity.getLocalClassName());
    }


    /**
     * 判断某个界面是否在前台
     *
     * @param activity 要判断的Activity
     * @return 是否在前台显示
     */
    public static boolean isForeground(Activity activity) {
        //System.out.println("activity.getLocalClassName()="+activity.getLocalClassName());
        return isForeground(activity, activity.getLocalClassName());
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
//        boolean flag=false;
        for (ActivityManager.RunningTaskInfo taskInfo : list) {
            if (taskInfo.topActivity.getShortClassName().contains(className)) { // 说明它已经启动了
//                flag = true;
                return true;
            }
        }
        return false;
    }


    public static boolean getTopApp(Context mContext, String lockAppName) {

        String topActivityName = "";
        ActivityManager am = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = am
                .getRunningTasks(1);
        if (runningTasks != null && !runningTasks.isEmpty()) {
            ActivityManager.RunningTaskInfo taskInfo = runningTasks.get(0);
            topActivityName = taskInfo.topActivity.getClassName();
        }
        System.out.println("topActivityName=" + topActivityName + "lockAppName=" + lockAppName);
        if (lockAppName.equals(topActivityName)) {
            return true;
        }
        return false;
    }

    //根据包名判断应用是否存在
    public static boolean checkApplication(Context mContext, String packageName) {
        if (packageName == null || "".equals(packageName)) {
            return false;
        }
        try {
            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    //判断activity是否存在
    public static boolean checkActivity(Context context, String packName, String className) {
        Intent intent = new Intent();
        intent.setClassName(packName, className);
        if (context.getPackageManager().resolveActivity(intent, 0) == null) {
            // 说明系统中不存在这个activity
            return false;
        }
        return true;
        /*
        方法二
         if (intent.resolveActivity(getPackageManager()) == null) {
            // 说明系统中不存在这个activity
          }

          方法三
          List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
            if (list.size() == 0) {
            // 说明系统中不存在这个activity
            }
        */
    }


    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }


    //尝试不加载音视频也获取时长
    public static long getMediaLength(String strMediaPath) {

        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        mmr.setDataSource(strMediaPath);
        String time = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        long timeInmillisec = Long.parseLong(time);
        return timeInmillisec;
    }

    public static boolean isApkDebugable(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {

        }
        return false;
    }


    public static String strToTime(String string) {
        int time_i = Integer.parseInt(string);
        return intToTime(time_i);
    }

    public static String intToTime(int time_i) {

        int h = time_i / (60 * 60);
        int m = (time_i % (60 * 60)) / 60;
        int s = time_i % 60;
        String str = "";
//        if( h < 10) {
//            str = "0" + h + ":";
//        } else if (h > 10){
//            str = str + h + ":";
//        }
        if (m < 10) {
            str = str + "0" + m + ":";
        } else {
            str = str + m + ":";
        }
        if (s < 10) {
            str = str + "0" + s;
        } else {
            str = str + s;
        }
        return str;
    }


    /**
     * 读取SD文件路径
     */
    public static String readFileFromSDCard(File file) {
        String result = null;
        try {
            StringBuffer sb = new StringBuffer();
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            result = sb.toString();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    public static String getApkSize(Integer size) {
        if (null == size) return "";

        long rest = 0;
        if (size < 1024) {
            return String.valueOf(size) + "B";
        } else {
            size /= 1024;
        }

        if (size < 1024) {
            return String.valueOf(size) + "KB";
        } else {
            rest = size % 1024;
            size /= 1024;
        }

        if (size < 1024) {
            size = size * 100;
            return String.valueOf((size / 100)) + "." + String.valueOf((rest * 100 / 1024 % 100)) + "MB";
        } else {
            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "GB";
        }
    }

    /**
     * 合并两张bitmap为一张
     *
     * @param background
     * @param foreground
     * @return Bitmap
     */
    public static Bitmap combineBitmap(Bitmap background, Bitmap foreground) {
        if (background == null || foreground == null) {
            return null;
        }
        int bgWidth = background.getWidth();
        int bgHeight = background.getHeight();
        int fgWidth = foreground.getWidth();
        int fgHeight = foreground.getHeight();
        int width = bgWidth;
        int height = bgHeight;
        if (bgWidth < fgWidth) {
            width = fgWidth;
        }
        if (bgHeight < fgHeight) {
            height = fgHeight;
        }
        Bitmap newmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);

        canvas.drawBitmap(background, 0, 0, null);
        canvas.drawBitmap(foreground, 0, 0, null);
        canvas.save();
        canvas.restore();
        return newmap;
    }

    public static Bitmap combineBitmap(Bitmap background, Bitmap foreground, int rect_width, int rect_height) {
        if (background == null || foreground == null) {
            return null;
        }
        int bgWidth = background.getWidth();
        int bgHeight = background.getHeight();
        int fgWidth = foreground.getWidth();
        int fgHeight = foreground.getHeight();
        int width = bgWidth;
        int height = bgHeight;
        if (bgWidth < fgWidth) {
            width = fgWidth;
        }
        if (bgHeight < fgHeight) {
            height = fgHeight;
        }

        float fScale = 1f;
        if (width > rect_width) {
            fScale = rect_width <= 0 ? 1f : rect_width * 1.0f / width;

            Matrix matrix = new Matrix();
            matrix.postScale(fScale, fScale); //长和宽放大缩小的比例
            background = Bitmap.createBitmap(background, 0, 0, background.getWidth(), background.getHeight(), matrix, true);
            foreground = Bitmap.createBitmap(foreground, 0, 0, foreground.getWidth(), foreground.getHeight(), matrix, true);

            bgWidth = background.getWidth();
            bgHeight = background.getHeight();
            fgWidth = foreground.getWidth();
            fgHeight = foreground.getHeight();

            width = bgWidth;
            height = bgHeight;
            if (bgWidth < fgWidth) {
                width = fgWidth;
            }
            if (bgHeight < fgHeight) {
                height = fgHeight;
            }
        }


        if (width < rect_width) {
            width = rect_width;
        }

        if (height < rect_height) {
            height = rect_height;
        }

        Bitmap newmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);

        Paint rect_paint = new Paint();
        rect_paint.setColor(Color.parseColor("#ffffff"));
        rect_paint.setStyle(Paint.Style.FILL);
        canvas.drawRect(new Rect(0, 0, width, height), rect_paint);

        canvas.drawBitmap(background, 0, 0, null);
        canvas.drawBitmap(foreground, 0, 0, null);
        canvas.save();
        canvas.restore();
        return newmap;
    }

    public static Bitmap combineBitmap(Bitmap foreground, int rect_width, int rect_height) {
        if (foreground == null) {
            return null;
        }
        int fgWidth = foreground.getWidth();
        int fgHeight = foreground.getHeight();
        int width = fgWidth;
        int height = fgHeight;

        float fScale = 1f;
        if (width > rect_width) {
            fScale = rect_width <= 0 ? 1f : rect_width * 1.0f / width;
            Matrix matrix = new Matrix();
            matrix.postScale(fScale, fScale); //长和宽放大缩小的比例
            LogUtils.e("宽高缩放：w = " + fgWidth + ", h = " + fgHeight + ", fs = " + fScale);
            foreground = Bitmap.createBitmap(foreground, 0, 0, foreground.getWidth(), foreground.getHeight(), matrix, true);

            fgWidth = foreground.getWidth();
            fgHeight = foreground.getHeight();
            width = fgWidth;
            height = fgHeight;
        }

        if (width < rect_width) {
            width = rect_width;
        }

        if (height < rect_height) {
            height = rect_height;
        }

        Bitmap newmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);

        Paint rect_paint = new Paint();
        rect_paint.setColor(Color.parseColor("#ffffff"));
        rect_paint.setStyle(Paint.Style.FILL);
        canvas.drawRect(new Rect(0, 0, width, height), rect_paint);

        canvas.drawBitmap(foreground, 0, 0, null);
        canvas.save();
        canvas.restore();
        return newmap;
    }


    /**
     * 获取本周开始时间
     *
     * @return
     */
    public static long getTimeOfWeekStart() {
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.HOUR_OF_DAY, 0);
        ca.clear(Calendar.MINUTE);
        ca.clear(Calendar.SECOND);
        ca.clear(Calendar.MILLISECOND);
        ca.setFirstDayOfWeek(Calendar.MONDAY);  //设置周一是一周的开始
        ca.set(Calendar.DAY_OF_WEEK, ca.getFirstDayOfWeek());
        return ca.getTimeInMillis();
    }

    /**
     * 获取每周第一天
     * @param date
     * @return
     */
    public static String getFirstDayOfWeek(String date) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal = Calendar.getInstance();
            cal.setTime(format.parse(date));
            int day = cal.get(Calendar.DAY_OF_WEEK);
            // 当周第一天是星期天 Calendar周日是每周的第一天
            if (day == 1) {
                day = 7;

            } else {
                day--;
            }
            // 周一
            cal.add(Calendar.DAY_OF_MONTH, -(day - 1));
            return format.format(cal.getTime());

        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }

    /**
     * 获取每周最后一天
     * @param date
     * @return
     */
    public static String getLastDayOfWeek(String date) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal = Calendar.getInstance();
            cal.setTime(format.parse(date));
            int day = cal.get(Calendar.DAY_OF_WEEK);
            // 当周第一天是星期天 Calendar周日是每周的第一天
            if (day == 1) {
                day = 7;
            } else {
                day--;
            }
            // 周日
            cal.add(Calendar.DAY_OF_MONTH, 7-day);
            return format.format(cal.getTime());

        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }
}
